package com.dream.utils.zxing;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import com.google.common.collect.Maps;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

public class ZxingUtils {

	// inner icon size
	private static final int ICON_SIZE = 80;
	
	private static final int ICON_HALF_SIZE = ICON_SIZE / 2;
	// barcode image size
	private static final int BARCODE_SIZE = 400;
	
	private static final int FRAME_WIDTH = 2;
	
	private static MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
	
	/**
	 * 产生二维码 不带图片
	 * 
	 * @author EvanYu
	 * @date 2014年6月13日
	 */
	public static void generatePic(String content, String path) {

		try {

			BitMatrix bitMatrix = getMatrix(content, multiFormatWriter);
			File file1 = new File(path);

			MatrixToImageWriter.writeToFile(bitMatrix, "png", file1);

		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		}
	}

	/**
	 * 产生二维码 带图片
	 * @param content
	 * @param path
	 * @param iconPath
	 */
	public static void generatePic(String content, String path,String iconPath){
		
		try {
			
			BufferedImage image = genBarcode(content,iconPath);
			File barFile = new File(path);
			ImageIO.write(image, "png", barFile);
			
		} catch (WriterException e) {
			throw new RuntimeException(e.getMessage());
		} catch (IOException e) {
			throw new RuntimeException(e.getMessage());
		}
	}


	private static BitMatrix getMatrix(String content, MultiFormatWriter multiFormatWriter) throws WriterException {

		Map<EncodeHintType, String> hints = Maps.newHashMap();
		hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
		BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, BARCODE_SIZE, BARCODE_SIZE, hints);
		return bitMatrix;

	}
	
	/**
	 * 压缩ICON
	 * @param iconPath
	 * @param hasFiller
	 * @return
	 * @throws IOException
	 */
	private static BufferedImage scale(String iconPath, boolean hasFiller) throws IOException {
		
		double ratio = 0.0; // 缩放比例
		File file = new File(iconPath);

		BufferedImage srcImage = ImageIO.read(file);
		Image destImage = srcImage.getScaledInstance(ICON_SIZE, ICON_SIZE, BufferedImage.SCALE_SMOOTH);
		// 计算比例
		if ((srcImage.getHeight() > ICON_SIZE) || (srcImage.getWidth() > ICON_SIZE)) {
			if (srcImage.getHeight() > srcImage.getWidth()) {
				ratio = (new Integer(ICON_SIZE)).doubleValue() / srcImage.getHeight();
			} else {
				ratio = (new Integer(ICON_SIZE)).doubleValue() / srcImage.getWidth();
			}
			AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null);
			destImage = op.filter(srcImage, null);
		}
		if (hasFiller) {// 补白
			BufferedImage image = new BufferedImage(ICON_SIZE, ICON_SIZE, BufferedImage.TYPE_INT_RGB);
			Graphics2D graphic = image.createGraphics();
			graphic.setColor(Color.white);
			graphic.fillRect(0, 0, ICON_SIZE, ICON_SIZE);
			if (ICON_SIZE == destImage.getWidth(null))
				graphic.drawImage(destImage, 0, (ICON_SIZE - destImage.getHeight(null)) / 2, destImage.getWidth(null),
						destImage.getHeight(null), Color.white, null);
			else
				graphic.drawImage(destImage, (ICON_SIZE - destImage.getWidth(null)) / 2, 0, destImage.getWidth(null),
						destImage.getHeight(null), Color.white, null);
			graphic.dispose();
			destImage = image;
		}
		return (BufferedImage) destImage;
	}
	
	/**
	 * 处理barcode
	 * @param content
	 * @param srcImagePath
	 * @return
	 * @throws WriterException
	 * @throws IOException
	 */
	private static BufferedImage genBarcode(String content,String srcImagePath) throws WriterException, IOException {
		
		// 读取源图像
		BufferedImage scaleImage = scale(srcImagePath, true);
		int[][] srcPixels = new int[ICON_SIZE][ICON_SIZE];
		for (int i = 0; i < scaleImage.getWidth(); i++) {
			for (int j = 0; j < scaleImage.getHeight(); j++) {
				srcPixels[i][j] = scaleImage.getRGB(i, j);
			}
		}
		
		
		Map<EncodeHintType, Object> hint = new HashMap<EncodeHintType, Object>();
		hint.put(EncodeHintType.CHARACTER_SET, "utf-8");
		hint.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
		
		// 生成二维码
		BitMatrix matrix = getMatrix(content,multiFormatWriter);

		// 二维矩阵转为一维像素数组
		int halfW = matrix.getWidth() / 2;
		int halfH = matrix.getHeight() / 2;
		int[] pixels = new int[BARCODE_SIZE * BARCODE_SIZE];

		for (int y = 0; y < matrix.getHeight(); y++) {
			for (int x = 0; x < matrix.getWidth(); x++) {
				// 读取图片
				if (x > halfW - ICON_HALF_SIZE && x < halfW + ICON_HALF_SIZE && y > halfH - ICON_HALF_SIZE
						&& y < halfH + ICON_HALF_SIZE) {
					pixels[y * BARCODE_SIZE + x] = srcPixels[x - halfW + ICON_HALF_SIZE][y - halfH + ICON_HALF_SIZE];
				}
				// 在图片四周形成边框
				else if ((x > halfW - ICON_HALF_SIZE - FRAME_WIDTH && x < halfW - ICON_HALF_SIZE + FRAME_WIDTH
						&& y > halfH - ICON_HALF_SIZE - FRAME_WIDTH && y < halfH + ICON_HALF_SIZE + FRAME_WIDTH)
						|| (x > halfW + ICON_HALF_SIZE - FRAME_WIDTH && x < halfW + ICON_HALF_SIZE + FRAME_WIDTH
								&& y > halfH - ICON_HALF_SIZE - FRAME_WIDTH && y < halfH + ICON_HALF_SIZE + FRAME_WIDTH)
						|| (x > halfW - ICON_HALF_SIZE - FRAME_WIDTH && x < halfW + ICON_HALF_SIZE + FRAME_WIDTH
								&& y > halfH - ICON_HALF_SIZE - FRAME_WIDTH && y < halfH - ICON_HALF_SIZE + FRAME_WIDTH)
						|| (x > halfW - ICON_HALF_SIZE - FRAME_WIDTH && x < halfW + ICON_HALF_SIZE + FRAME_WIDTH
								&& y > halfH + ICON_HALF_SIZE - FRAME_WIDTH && y < halfH + ICON_HALF_SIZE + FRAME_WIDTH)) {
					pixels[y * BARCODE_SIZE + x] = 0xfffffff;
				} else {
					// 此处可以修改二维码的颜色，可以分别制定二维码和背景的颜色；
					pixels[y * BARCODE_SIZE + x] = matrix.get(x, y) ? 0xff000000 : 0xfffffff;
				}
			}
		}

		BufferedImage image = new BufferedImage(BARCODE_SIZE, BARCODE_SIZE, BufferedImage.TYPE_INT_RGB);
		image.getRaster().setDataElements(0, 0, BARCODE_SIZE, BARCODE_SIZE, pixels);

		return image;
	}
}
